package cn.com.ninng;

import java.util.HashMap;
import java.util.Map;

/**
 * 罗马数字转整数
 * @author liulekang
 * @createdate 2021/7/28
 */
public class Problem13 {

    public static void main(String[] args) {
        System.out.println(romanToInt("MCMXCIV"));
    }


    public static int romanToInt(String str) {

        if (str ==null || str.length() <= 0){
            return -1;
        }

        Map<String, Integer> maps = new HashMap<>();
        maps.put("I",1);
        maps.put("V",5);
        maps.put("X",10);
        maps.put("L",50);
        maps.put("C",100);
        maps.put("D",500);
        maps.put("M",1000);

        //从右到左进行解析，如果左比右大，则+左；如果左比右小，则-左

        char[] chars = str.toCharArray();

        int sum = 0;
        int r = 0;
        for (int i = chars.length -1; i>=0;i--){
            Integer num = maps.get(String.valueOf(chars[i]));
            if( r > num) {
                sum -=  num;
            }else {
                sum +=  num;
            }
            r = num;
        }
        return sum;
    }
}
